import { Component, OnInit } from '@angular/core';
import { AlertController, NavController } from '@ionic/angular';
import { HttpService } from '../../../service/http.service';
import { WechatService } from '../../../service/wechat.service';
import { ToastService } from '../../../service/toast.service';
import { TranslateService } from '@ngx-translate/core';
import {ActivatedRoute} from '@angular/router';
import {Device} from '@ionic-native/device/ngx';

@Component({
    selector: 'app-patient-login',
    templateUrl: './patient-login.page.html',
    styleUrls: ['./patient-login.page.scss'],
})
export class PatientLoginPage implements OnInit {
    aPhone = '';
    aPassword = '';
    wxInstall = false;
    sysLang = '';
    loginForAppoint = false;
    isNativeRun = false;
    showPatientLogin = false;

    constructor(
        private activatedRoute: ActivatedRoute,
        private navController: NavController,
        private httpService: HttpService,
        private toastSrv: ToastService,
        private alertController: AlertController,
        private wechatSrv: WechatService,
        private translate: TranslateService,
        private device: Device,
    ) {
        activatedRoute.queryParams.subscribe(queryParams => {
            this.loginForAppoint = !!queryParams.loginForAppoint;
            this.showPatientLogin = !!queryParams.showPatientLogin;
        });
        this.isNativeRun = !!this.device.platform;
    }

    async ngOnInit() {
        this.sysLang = this.translate.getBrowserCultureLang().toLowerCase();

        try {
            if (this.device.platform) {
                this.wxInstall = await this.wechatSrv.wechatIsInstall();
            }
        } catch (e) {
            this.toastSrv.showToast(e);
        }
    }

    public async toPatient() {
        if (this.sysLang === 'en-us') {
            if (!this.aPhone) {
                this.toastSrv.showToast('Please Enter Phone Number');
                return;
            }
            if (!this.aPassword) {
                this.toastSrv.showToast('Please Enter Password');
                return;
            }
        } else {
            if (!this.aPhone) {
                this.toastSrv.showToast('请输入手机号');
                return;
            }
            if (!this.aPassword) {
                this.toastSrv.showToast('请输入密码');
                return;
            }
        }
        const result: any = await this.httpService.post()
            .setPath('/pub/user/userLogin')
            .setBody({
                phone: this.aPhone,
                password: this.aPassword,
                userType: 1
            })
            .request();

        if (result.status === 0) {
            this.aPhone = '';
            this.aPassword = '';
            const loginInfo = result.data;
            localStorage.setItem('userId', loginInfo.userId);
            localStorage.setItem('userType', loginInfo.type);
            localStorage.setItem('auth-token', loginInfo.authToken);
            localStorage.setItem('redirectTo', '/patient-app');

            if (this.loginForAppoint) {
                localStorage.setItem('appointAndLogin', '/patient-app');
                await this.navController.navigateBack('/patient-registion-times');
            } else {
                await this.navController.navigateRoot('/patient-app');
            }
        }
    }

    public async forgetPassword() {
        await this.navController.navigateForward('/patient-password', {
            queryParams: { isForgetPassword: '0' }
        });
    }

    async registerNow() {
        await this.navController.navigateForward('/patient-register');
    }

    public async wechatLogin() {
        try {
            const authResult: any = await this.wechatSrv.wechatAuthLogin();
            if (authResult.code) {
                const result: any = await this.httpService.post()
                    .setPath('/pub/user/wxLogin')
                    .setBody({
                        wxCode: authResult.code
                    })
                    .request();

                if (result.status === 0) {
                    const loginInfo = result.data;
                    localStorage.setItem('userId', loginInfo.userId);
                    localStorage.setItem('userType', loginInfo.type);
                    localStorage.setItem('auth-token', loginInfo.authToken);
                    localStorage.setItem('redirectTo', '/patient-app');
                    await this.navController.navigateRoot('/patient-app');
                    // await this.navController.navigateRoot('/patient-person-edit', {
                    //     queryParams: { dataType: 'phone', value: '' }
                    // });
                }
            }
        } catch (e) {
            this.toastSrv.showToast(e);
        }
    }

    public toPrivacy() {
        this.navController.navigateForward(['privacy']);
    }

}
